package voldemort.store.cachestore;

/**
 * Created by IntelliJ IDEA.
 * User: thsieh
 * Date: May 13, 2010
 * Time: 11:23:51 AM
 * To change this template use File | Settings | File Templates.
 */

import voldemort.utils.ByteArray;

import java.lang.reflect.Array;

import static voldemort.store.cachestore.BlockUtil.KeyType;

public final class Key<T> {

    // generic type
    private T key;

    /**
     * version 0, means dont' care version
     * @param key
     */
    private Key(T key) {
        this.key =key;
    }


    public static Key createKey(int key) {
        return new Key( new Integer(key));
    }

    public static Key createKey(long key) {
        return new Key( new Long(key));
    }


    public static Key createKey(String key) {
        return new Key( key);
    }

    public static Key createKey(ByteArray array) {
        return new Key(array);
    }

    public static Key createKey(Object key) {
        if ( key instanceof Array) throw new StoreException("Array type is not supported");
        return new Key( key);
    }


    public T getKey() {
        return key;
    }

    @Override
    public int hashCode() {
        return key.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if(this == obj)
            return true;
        if ( obj instanceof Key )
            return key.equals( ((Key) obj).getKey());
        else
           return false;
    }

    public KeyType getType() {
        return getKeyType(key);
    }


    @Override
    public String toString() {
        return key.toString()+" "+ getKeyType(key);
    }

    public static KeyType getKeyType(Object object) {
        if ( object instanceof Integer) return KeyType.INT;
        else if ( object instanceof Long ) return KeyType.LONG;
        else if ( object instanceof String) return KeyType.STRING;
        else if ( object instanceof ByteArray) return KeyType.BARRAY;
        else  return KeyType.OBJECT;
    }

}
